package com.example.androidproject.data.bean;

import android.content.Context;
import android.os.CountDownTimer;

import com.example.androidproject.MyApp;
import com.example.androidproject.data.response.LoginResponse;
import com.hyg.base.ui.base.BaseActivity;
import com.hyg.common.utils.SPUtils;
import com.hyg.idea.net.token.RefreshTokenResponse;


public class UserInfoTools {
    private static UserInfoBean sUserInfoBean;

    public static void init(Context context) {
        sUserInfoBean = getUserInfoBean(context);
        if (sUserInfoBean == null) {
            sUserInfoBean = new UserInfoBean();

            sUserInfoBean.setTokenId("");
        }
        setUserInfoBean(context, sUserInfoBean);
    }

    private static UserInfoBean getUserInfoBean(Context context) {
        if (sUserInfoBean == null) {
            sUserInfoBean = SPUtils.getObject(UserInfoBean.class);
        }
        if (sUserInfoBean == null) {
            sUserInfoBean = new UserInfoBean();
        }
        return sUserInfoBean;
    }

    /**
     * Save user info to SharedPreferences
     */
    private static void setUserInfoBean(Context context, UserInfoBean userInfoBean) {
        sUserInfoBean = userInfoBean;
        SPUtils.putObject(sUserInfoBean);
    }

    /**
     * login success，save user information to SharedPreferences and post
     * an event to update UI
     */
    public static void login(Context context, LoginResponse response) {
        sUserInfoBean.setLogin(true);
        sUserInfoBean.setUser(response.getUser());
        setUserInfoBean(context, sUserInfoBean);
    }

    /**
     * Logout and clear data，post an Event to update UI
     */
    public static void logout(){
//        if(BaseActivity.getCurrentActivity() != null && BaseActivity.getCurrentActivity() instanceof LoginActivity) return;
        SPUtils.remove(sUserInfoBean.getClass().getSimpleName());
        sUserInfoBean=null;
        init(MyApp.getApp());
        if(BaseActivity.getCurrentActivity() != null){
//            LoginActivity.launch(BaseActivity.getCurrentActivity());
        }else {
            new CountDownTimer(200,200){
                @Override
                public void onTick(long millisUntilFinished) {
                }
                @Override
                public void onFinish() {
                    if(BaseActivity.getCurrentActivity() != null){
//                        LoginActivity.launch(BaseActivity.getCurrentActivity());
                    }
                }
            }.start();
        }
    }

    /**
     * update token
     * @param response token response
     */
    public static void updateToken(RefreshTokenResponse response){
        SPUtils.putString("token", response.getToken());
    }

    public static String getToken(){
        return SPUtils.getString("token", "");
    }
}
